package org.biubiu0002.baiblog.im.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.FullHttpRequest;
import org.apache.commons.lang3.StringUtils;
import org.biubiu0002.baiblog.im.constants.RedisConstants;
import org.biubiu0002.baiblog.im.dto.ImUserDto;
import org.biubiu0002.baiblog.im.service.AuthService;
import org.biubiu0002.baiblog.im.session.ServerSession;
import org.biubiu0002.baiblog.im.utils.HttpHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author: biubiu0002
 * @Date: 2022/10/25 12:30
 **/
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean auth(ServerSession session, FullHttpRequest fullHttpRequest) {
        Channel channel = session.getChannel();
        boolean isValid = HttpHelper.checkRequest(channel, fullHttpRequest);
        if(!isValid){
            return false;
        }
        String uri = fullHttpRequest.uri();
        int accessTokenIndex = uri.lastIndexOf("access_token");
        String accessToken = uri.substring(accessTokenIndex + 13);
        String tokenKey = RedisConstants.getTokenKey(accessToken);
        String json = redisTemplate.opsForValue().get(tokenKey);
        if (StringUtils.isBlank(json)) {
            HttpHelper.sendBizException(channel, "A0100", "用户不存在，或用户名密码错误，请检查用户名或密码");
            return false;
        }
        ImUserDto imUserDto = JSON.parseObject(json, new TypeReference<ImUserDto>() {
        });
        //登录成功 不返回成功报文 后续websocket握手连接处理再发101升级报文
        session.setUser(imUserDto);
        channel.attr(ServerSession.SESSION_KEY).set(session);
        //其他登录成功的处理 在握手成功后处理
        return true;
    }
}
